package com.pirestupppai.network;

import android.content.Intent;

import com.pirestupppai.base.BaseApplication;
import com.pirestupppai.bean.LoginUser;
import com.pirestupppai.ui.activity.InputPhoneActivity;

import java.io.IOException;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 添加统一参数
 * verify验证参数
 * token头
 *
 * 如果只有token的话,也可以直接在NetworkRequest添加
 *
 * author: xiaoluo
 * date: 2017-03-15 10:45
 */
public class TupaiInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request original = chain.request();
        HttpUrl url;

//        Request oldRequest = chain.request();
//        String oldUrl = oldRequest.url().toString();
//        StringBuilder sb = new StringBuilder();
//
//        // 添加verify
//        if (oldUrl.indexOf("?") != -1) {
//            String[] thumb = oldUrl.split("\\?");
//            String[] keys = thumb[1].split("&");
//            Arrays.sort(keys);
//            for (String s : keys) {
//                if (s.indexOf("=") != -1) {
//                    sb.append(s.split("=").length >= 2 ? s.split("=")[1] : "");
//                }
//            }
//            Calendar cal = Calendar.getInstance();
//            sb.append(StringUtil.toMd5(Constant.SIGN));
//            sb.append(cal.get(Calendar.DATE));
//
//            url = original.url().newBuilder()
//                    .addQueryParameter("v", "2")
//                    .addQueryParameter("verify", StringUtil.toMd5(StringUtil.toMd5(
//                            sb.toString().toLowerCase()).toLowerCase()).toLowerCase())
//                    .build();
//        } else {
            url = original.url().newBuilder()
                    .build();
//        }

        // 添加token
        Request request = original.newBuilder()
                .addHeader("token", LoginUser.TokenVerity.getToken() + "")
                .method(original.method(), original.body())
                .url(url)
                .build();

        Response response = chain.proceed(request);
        // 登录态失效拦截
        if (response.code() == 401) {
            LoginUser.TokenVerity.setToken("");
            Intent intent = new Intent(BaseApplication.getAppContext(), InputPhoneActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            BaseApplication.getAppContext().startActivity(intent);
            throw new APIException("登录态失效");
        }
        return response;
    }

}

